<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
require_once ('./application/controllers/authenticate.php');
class Chapter extends Authenticate {
	
	const CHAPTER_PAGE_RANGE = 20;
	
	function __construct() {
		parent::__construct ();
		$this->load->model ( 'manga_model' );
		$this->load->model ( 'group_translator_model' );
		$this->load->model ( 'manga_chapter_model' );
		$this->load->library ( 'html/control/fx_control' );
		$this->load->library ( 'html/control/fx_filter' );
		$this->load->library ( 'html/control/fx_sort' );
		$this->manga_chapter_model->addAttributeOrder ( 'id', 'desc' );
		$this->load->library ( 'upload' );
		// Load Manga Model
		$this->loadCurrentChapter ();
	}
	
	public function loadCurrentChapter() {
		try {
			// Load Manga Model
			$id = $this->input->getParam ( 'id' );
			if ($id) {
				$this->manga_chapter_model->loadByPK ( $id );
				$this->st_registry->register ( 'admin/catalog/chapter/id', $id );
			} else {
				if ($id = $this->st_registry->registry ( 'admin/catalog/chapter/id' )) {
					$this->manga_chapter_model->loadByPK ( $id );
				}
			}
			return $this->manga_chapter_model;
		} catch ( Exception $ex ) {
			return null;
		}
	}
	
	protected function _eventLoadLayout() {
		$this->page ['title'] = 'Chapter Management';
		$this->module ['title'] = 'Chapter Management';
		$this->module ['grid'] ['records'] = 20;
		$this->module ['grid'] ['page_range'] = 5;
	}
	
	function index() {
		$data = $this->_initGridView ();
		$this->setPageContent ( 'catalog/chapter/grid', $data );
		$this->renderLayout ();
	}
	
	protected function _initGridView() {
		
		// Get Paginator Params
		$page = $this->input->getParam ( 'page' );
		$recordPerPage = $this->input->getParam ( 'recordPerPage' );
		if (! $recordPerPage) {
			$recordPerPage = $this->module ['grid'] ['records'];
		}
		
		// Get Filter Params
		$filters = $this->input->post ( 'chapterFilter' );
		// Filter
		$this->fx_filter->filter ( $filters, $this->manga_chapter_model );
		
		// Get Order Params
		$order = $this->input->post ( 'chapterOrder' );
		// Sort
		$this->fx_sort->sort ( $order, $this->manga_chapter_model );
		// Get total found records
		$found = $this->manga_chapter_model->countTotal ();
		
		// Paginate
		$this->load->library ( "tree/paginator/engine/st_paginator_collection" );
		$this->load->library ( "tree/paginator/st_paginator" );
		$this->st_paginator_collection->setModel ( $this->manga_chapter_model );
		$this->st_paginator->setConfig ( array ('engine' => $this->st_paginator_collection, 'pageRange' => $this->module ['grid'] ['page_range'], 'itemCountPerPage' => $recordPerPage, 'currentPageNumber' => $page ) );
		
		// Paginate Collection
		$collection = $this->st_paginator->getItemsByPage ( $page );
		if (empty ( $collection )) {
			$collection = array ();
		}
		$data = array ();
		$data ['found'] = $found;
		$data ['sorter'] = $this->fx_sort;
		$data ['filters'] = $this->fx_filter;
		$data ['paginator'] = $this->st_paginator;
		$data ['chapter_ids'] = $this->input->post ( 'chapter_ids' );
		$data ['chapter_ids_array'] = explode ( ',', $this->input->post ( 'chapter_ids' ) );
		$data ['collection'] = $collection;
		return $data;
	
	}
	
	public function edit() {
		try {
			// Reset Manga Selected
			//$this->st_registry->clearRegistry('admin/catalog/chapter/manga/selected');
			$data = $this->_initGridView ();
			$data ['manga'] = $this->manga_model->getCollection ();
			$this->load->view ( 'catalog/chapter/edit', $data );
		} catch ( Exception $ex ) {
			echo $ex->getMessage ();
		}
	}
	
	/*Select manga from gridview*/
	public function manga() {
		if ($id = $this->st_registry->registry ( 'admin/catalog/chapter/id' )) {
			$this->manga_chapter_model->loadByPK ( $id );
		}
		// Get Paginator Params
		$page = $this->input->getParam ( 'page' );
		$recordPerPage = $this->input->getParam ( 'recordPerPage' );
		if (! $recordPerPage) {
			$recordPerPage = 20;
		}
		// Get Filter Params	
		$filters = $this->input->post ( 'mangaFilter' );
		// Filter
		$this->fx_filter->filter ( $filters, $this->manga_model );
		// Get Order Params
		$order = $this->input->post ( 'mangaOrder' );
		// Sort
		$this->fx_sort->sort ( $order, $this->manga_model );
		// Get total found records
		$found = $this->manga_model->countTotal ();
		// Paginate
		$this->load->library ( "tree/paginator/engine/st_paginator_collection" );
		$this->load->library ( "tree/paginator/st_paginator" );
		$this->st_paginator_collection->setModel ( $this->manga_model );
		$this->st_paginator->setConfig ( array ('engine' => $this->st_paginator_collection, 'pageRange' => 5, 'itemCountPerPage' => $recordPerPage, 'currentPageNumber' => $page ) );
		// Paginate Collection
		$collection = $this->st_paginator->getItemsByPage ( $page );
		if (empty ( $collection )) {
			$collection = array ();
		}
		$data = array ();
		$data ['found'] = $found;
		
		/*RADIO SELECTED*/
		// Load manga radio button checked 
		$data ['manga_selected'] = $this->input->post ( 'manga_selected' );
		// If not check radio button
		if ($data ['manga_selected'] == 0) {
			// Check parameter in session
			$data ['manga_selected'] = $this->st_registry->registry ( 'admin/catalog/chapter/manga/selected' );
			// Then no checked
			if (! $data ['manga_selected']) {
				$data ['manga_selected'] = $this->manga_chapter_model->getMangaId ();
			}
		} else {
			// Check by parameter in session
			$this->st_registry->register ( 'admin/catalog/chapter/manga/selected', $data ['manga_selected'] );
		}
		
		/*END RADIO SELECTED*/
		
		$data ['model'] = $this->manga_chapter_model;
		$data ['sorter'] = $this->fx_sort;
		$data ['filters'] = $this->fx_filter;
		$data ['paginator'] = $this->st_paginator;
		$data ['collection'] = $collection;
		$this->load->view ( 'catalog/chapter/edit/manga', $data );
	}
	
	public function selectManga() {
		$output = 'Manga Selected: You not choose manga';
		$id = $this->input->post ( 'value' );
		$this->st_registry->register ( 'admin/catalog/chapter/manga/selected', $id );
		if ($this->manga_model->loadByPK ( $id )->isLoaded ()) {
			$output = 'Manga Selected: <a href="' . $this->manga_model->getMangaUrl () . '">' . $this->manga_model->getName () . '</a>';
		}
		echo $output;
	}
	
	public function resetmanga() {
		if ($id = $this->st_registry->registry ( 'admin/catalog/chapter/id' )) {
			$this->manga_chapter_model->loadByPK ( $id );
		}
		if ($this->manga_chapter_model->isLoaded ()) {
			$this->manga_chapter_model->updateField ( 'manga_id', 0 );
		}
		$this->st_registry->clearRegistry ( 'admin/catalog/chapter/manga/selected' );
		$output = 'Manga Selected: You not choose manga';
		echo $output;
	}
	
	public function grid() {
		try {
			//Get Data
			$data = $this->_initGridView ();
			//Transfer To View
			$this->load->view ( 'catalog/chapter/ajax/grid', $data );
		} catch ( Exception $ex ) {
			echo $ex->getMessage ();
		}
	}
	
	public function save() {
		try {
			// Load Chapter Model
			$id = $this->input->post ( 'id' );
			if ($id) {
				$this->manga_chapter_model->loadByPK ( $id );
			} else {
				$this->manga_chapter_model->setCreatedAt ( "NOW()" );
			}
			$data = $this->input->post ( 'chapter' );
			unset ( $data ['pages'] ['0'] );
			$jsonPages = $this->manga_chapter_model->parseArrayToPageIndexers ( $data ['pages'] );
			unset ( $data ['pages'] );
			if (is_array ( $data ) && count ( $data ) > 0) {
				$mangaId = $this->st_registry->registry ( 'admin/catalog/chapter/manga/selected' );
				$this->manga_chapter_model->setMangaId ( $mangaId );
				if ($this->admin_model->isLoaded ()) {
					$this->manga_chapter_model->setUserUploadId ( $this->admin_model->getId () );
				}
				$this->manga_chapter_model->setEntireData ( $data );
				$this->manga_chapter_model->setPageIndexes ( addslashes ( $jsonPages ) );
				$this->manga_chapter_model->setUpdatedAt ( "NOW()" );
				$this->manga_chapter_model->save ();
			}
			redirect ( site_url ( "admin/catalog/chapter/edit/id/" . $this->manga_chapter_model->getId (), true ) );
		} catch ( Exception $ex ) {
			echo $ex->getMessage ();
		}
	}
	
	public function massDelete() {
		try {
			// Load Manga Model
			$ids = $this->input->getMassValues ( 'chapter_ids' );
			if ($ids) {
				$this->manga_chapter_model->query ( "delete from catalog_manga_chapter where id in ($ids)" );
			}
			$countItem = count ( explode ( ',', $ids ) );
			$this->st_registry->register ( 'admin/catalog/chapter/message', "Delete $countItem items successfully" );
			redirect ( site_url ( "admin/catalog/chapter/index", true ) );
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/catalog/chapter/message', $e->getMessage () );
			redirect ( site_url ( "admin/catalog/chapter/index", true ) );
		}
	}
	
	public function massSetManga() {
		try {
			// Load Manga Model
			$ids = $this->input->getMassValues ( 'chapter_ids' );
			$mangaId = $this->input->post ( 'mangaSetterId' );
			if ($ids && $mangaId != 0) {
				$this->manga_chapter_model->query ( "update catalog_manga_chapter set manga_id = $mangaId where id in ($ids)" );
			}
			$countItem = count ( explode ( ',', $ids ) );
			$this->st_registry->register ( 'admin/catalog/chapter/message', "Update $countItem items successfully" );
			redirect ( site_url ( "admin/catalog/chapter/index", true ) );
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/catalog/chapter/message', $e->getMessage () );
			redirect ( site_url ( "admin/catalog/chapter/index", true ) );
		}
	}
	
	public function delete() {
		try {
			if ($this->manga_chapter_model->isLoaded ()) {
				$name = $this->manga_chapter_model->getName ();
				$this->manga_chapter_model->delete ();
				$this->st_registry->register ( 'admin/catalog/chapter/message', "Delete Chapter $name successfully" );
				redirect ( site_url ( "admin/catalog/chapter/index", true ) );
			} else {
				$this->st_registry->register ( 'admin/catalog/chapter/message', "Delete chapter successfully" );
				redirect ( site_url ( "admin/catalog/chapter/index", true ) );
			}
		} catch ( Exception $ex ) {
			$this->st_registry->register ( 'admin/catalog/chapter/message', "Error when deleting chapter" );
			redirect ( site_url ( "admin/catalog/chapter/index", true ) );
		}
	}
}